import re

from lxml.html import parse
from io import StringIO
import subprocess

from pagamigo.RequestSession import RequestSession
import pagamigo.validator as Validator
from pagamigo.captcha import handle_captcha

ID = "login"

ARGS = {
    "username": ("Username (email address)", "username", Validator.email),
    "password": ("Password", "password", lambda x: len(x) > 0),
    "country": ("Country", "country", None),
}


def flow(session, username, password, country):
    session.set_module("/us/home", "Login", 2)

    auth_url = "/signin?country.x=" + country + "&locale.x=" + "en_US"

    auth_page = session.request(
        auth_url, False, {}, mock_resp="resps/login.html", plain_headers=True)

    session.referer = auth_url

    resp = session.request(auth_url, True, {
        "_csrf": re.search('_csrf" value="(.*?)"', auth_page).group(1),
        "locale.x": "en_US",
        "processSignin": "main",
        "fn_sync_data": "fn_sync_data",
        "intent": "signin",
        "ads-client-context": "signin",
        "requestUrl": auth_url,
        "forcePhonePasswordOptIn": "",
        "login_email": username,
        "login_password": password,
        "btnLogin": "Login",
        "splitLoginContext": "inputPassword",
        "splitLoginCookiedFallback": "true"
    }, plain_headers=True, like_form=True, mock_resp="resps/recaptcha.html")

    handle_captcha(session, resp, mock=session.mock)
